from rest_framework import viewsets, status
from rest_framework.decorators import action
from rest_framework.permissions import AllowAny
from rest_framework_simplejwt.tokens import RefreshToken
from django.contrib.auth import get_user_model
from django.core.files.base import ContentFile
from django.conf import settings
import base64
import os
from datetime import datetime
from .serializers import UserSerializer, UserRegisterSerializer
from utils.response import api_response
from utils.wechat import get_wx_access_token
from rest_framework.decorators import permission_classes
User = get_user_model()

class UserViewSet(viewsets.ModelViewSet):
    queryset = User.objects.all()
    serializer_class = UserSerializer

    def get_permissions(self):
        if self.action in ['wx_login', 'register', 'upload_avatar']:
            return [AllowAny()]
        return super().get_permissions()

    @action(detail=False, methods=['post'])
    @permission_classes([AllowAny])
    def upload_avatar(self, request):
        try:
            # 获取base64图片数据和文件名
            avatar_data = request.data.get('avatar')
            file_name = request.data.get('file_name')
            
            if not avatar_data or not file_name:
                return api_response(400, "缺少必要参数")

            # 确保文件名是jpg格式
            if not file_name.lower().endswith(('.jpg', '.jpeg')):
                file_name = f"{os.path.splitext(file_name)[0]}.jpg"

            # 解码base64数据
            try:
                image_data = base64.b64decode(avatar_data)
            except Exception as e:
                return api_response(400, "图片数据格式错误")

            # 构建保存路径
            save_dir = os.path.join(settings.MEDIA_ROOT, 'avatars')
            if not os.path.exists(save_dir):
                os.makedirs(save_dir)

            # 生成唯一文件名
            timestamp = datetime.now().strftime('%Y%m%d%H%M%S')
            unique_filename = f"{timestamp}_{file_name}"
            file_path = os.path.join(save_dir, unique_filename)

            # 保存文件
            with open(file_path, 'wb') as f:
                f.write(image_data)

            # 生成访问URL
            avatar_url = f"{settings.MEDIA_URL}avatars/{unique_filename}"

            return api_response(data={'url': avatar_url})
        except Exception as e:
            return api_response(500, f"上传失败：{str(e)}")

    @action(detail=False, methods=['post'])
    def wx_login(self, request):
        code = request.data.get('code')
        if not code:
            return api_response(400, "缺少code参数")

        # 获取微信openid
        wx_res = get_wx_access_token(code)
        if 'errcode' in wx_res:
            return api_response(400, wx_res.get('errmsg', '微信登录失败'))

        openid = wx_res['openid']
        try:
            user = User.objects.get(openid=openid)
            # 生成JWT token
            refresh = RefreshToken.for_user(user)
            return api_response(data={
                'token': str(refresh.access_token),
                'refresh': str(refresh),
                'user': UserSerializer(user).data
            })
        except User.DoesNotExist:
            return api_response(404, "用户未注册", {"openid": openid})

    @action(detail=False, methods=['post'])
    def register(self, request):
        serializer = UserRegisterSerializer(data=request.data)
        if serializer.is_valid():
            user = serializer.save()
            # 生成JWT token
            refresh = RefreshToken.for_user(user)
            return api_response(data={
                'token': str(refresh.access_token),
                'refresh': str(refresh),
                'user': UserSerializer(user).data
            })
        return api_response(400, str(serializer.errors)) 